package com.cheerscpl.network;

import com.cheerscpl.Constants;
import com.cheerscpl.protocol.model.DataPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by chenpuliang on 2017/6/3.
 */
public class Encoder extends MessageToMessageEncoder<DataPacket> {

    @Override
    protected void encode(ChannelHandlerContext ctx, DataPacket msg, List<Object> out) throws Exception {
        if(msg != null){
            String message = conversDataPacket(msg);
            ByteBuf buf = ctx.alloc().buffer();
            buf.writeBytes(message.getBytes());
            ctx.writeAndFlush(buf);
        }
    }

    private String conversDataPacket(DataPacket dataPacket){
        if(dataPacket != null){
            StringBuffer buffer = new StringBuffer();
            buffer.append(Constants.PREFIX)
                    .append(dataPacket.getDevId())
                    .append(new SimpleDateFormat("yyMMddhhmmss").format(new Date()))
                    .append(dataPacket.getLength())
                    .append(dataPacket.getFid())
                    .append(dataPacket.getMsgId());
            return buffer.toString();
        }else {
            return null;
        }
    }
}
